package uk.co.hs.web.initializer;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Class to initialise the application (assuming Spring has already loaded
 * itself)
 */
public class ApplicationControlListener implements javax.servlet.ServletContextListener
{

 private Controller mController;

 private ApplicationContext mContext;

 private static final String STARTER = "hs_controller";

 private Logger mLogger = LoggerFactory.getLogger(getClass());

 /**
  * Called when context is started
  *
  * @see javax.servlet.ServletContextListener#
  *      contextInitialized(javax.servlet.ServletContextEvent) {@inheritDoc}
  */
 public void contextInitialized(ServletContextEvent aEvent)
 {
  ServletContext context = aEvent.getServletContext();
  mContext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
  mLogger.info("Starting controller");
  mController = (Controller) mContext.getBean(STARTER);
  mController.start();

 }

 /**
  * Called when context is shut down
  *
  * @see javax.servlet.ServletContextListener#
  *      contextDestroyed(javax.servlet.ServletContextEvent) {@inheritDoc}
  */
 public void contextDestroyed(ServletContextEvent event)
 {
  if (mController != null)
  {
   mLogger.info("Shutting down controller");
   mController.shutdown();
  }
 }
}